<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="configurationCoding">
            <span slot="label">
              {{ $t('配置编码') }}
            </span>
            <el-input v-model="form.configurationCoding" :disabled="form.id !== undefined && form.id !== null && form.id !== ''" :placeholder="$t('配置编码')" show-word-limit maxlength="32" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('配置类型')" prop="fileConfigType">
            <dict-select
              v-model="form.fileConfigType"
              :disabled="form.id !== undefined && form.id !== null && form.id !== ''"
              dictionary="file_config_type"
              :placeholder="$t('配置类型')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="form.fileConfigType === 'WDJJ' ? $t('必传附件') : $t('文档类型')" prop="documentType">
            <treeselect
              v-model="form.documentType"
              :options="fileDirOptions"
              :load-options="loadOptions"
              :default-expand-level="0"
              class="topSearchTree"
              :flat="true"
              :multiple="isMultiple"
              :placeholder="$t('文档类型')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.fileConfigType === 'WDJJ'" :label="$t('选传附件')" prop="documentNonType">
            <treeselect
              v-model="form.documentNonType"
              :options="fileDirOptions"
              :load-options="loadOptions"
              :default-expand-level="0"
              class="topSearchTree"
              :flat="true"
              :multiple="isMultiple"
              :placeholder="$t('文档类型')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.fileConfigType === 'LCJD'" :span="12">
          <el-form-item :label="$t('业务类型')" prop="nodeType">
            <el-select v-model="form.nodeType" filterable clearable collapse-tags @change="changeNodeType(true)">
              <el-option
                v-for="item in wfConfigFlowOption"
                :key="item.id"
                :label="item.busDataTypeLabel"
                :value="item.busDataType"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.fileConfigType === 'LCJD'" :span="12">
          <el-form-item :label="$t('绑定节点')" prop="nodeId">
            <treeselect
              v-model="form.nodeId"
              :options="allNodeList"
              value-consists-of="LEAF_PRIORITY"
              :multiple="false"
              :load-options="loadOptions"
              :default-expand-level="0"
              :placeholder="$t('绑定节点')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">{{ $t('说明') }}</el-divider>
          <p>文档沉淀: file_tree, 例如发票的上传按钮.无法选择对应的沉淀目录, 可以通过改配置. 让发票文件沉淀到指定的目录下</p>
          <p>文档校验: file_config, 例如某个表单需要设置必传附件, 配置后如未按规定上传无法提交表单</p>
          <p>默认分类: file_select, 在表单的附件列表中, 上传界面只展示规定的文件分类目录. 强制规范用户可以上传到那些目录中</p>
          <p>流程节点绑定: file_node, 仅在项目流程中有效, 例如在填写某个流程节点的表单时, 需要默认上传到指定目录中, 配置后用户不必再选择文件分类, 直接上传附件即可</p>
          <p>规范: 编码默认以下列字段开头, 例如: file_tree_xxx, 这里的xxx表示为附件的dataType值</p>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="sys:config" />
    </div>
  </div>
</template>

<script>
    import { saveFileConfig, getFileConfig, findByConfigurationCoding } from '@/api/file/fileConfig/fileConfig'
    import Treeselect from '@riophae/vue-treeselect'
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    import { fileClassTreeStructure } from '@/api/file/filefolder/folder'
    import { listWfConfigNode } from '@/api/act/busFlow/wfConfigNode'
    import { listWfConfigFlow } from '@/api/act/busFlow/wfConfigFlow'
    export default {
      components: {
        Treeselect
      },
      data() {
        return {
          // 表单参数
          form: {},
          // 遮罩层
          loading: false,
          // 配置类型字典
          fileConfigTypeOptions: [],
          // 所有节点-流程依赖节点选择使用
          allNodeList: [],
          wfConfigFlowOption: [],
          // 表单校验
          rules: {
            configurationCoding: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }, { validator: this.checkConfigurationCoding, trigger: 'blur' }],
            fileConfigType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            documentType: [{ required: true, validator: this.checkDocumentType, trigger: 'blur' }],
            remark: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            nodeType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            nodeId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
          },
          // 该业务的默认附件类型
          fileDirOptions: []
        }
      },
      computed: {
        isMultiple() {
          return this.form.fileConfigType === 'WDJJ' || this.form.fileConfigType === 'MRFL'
        }
      },
      created() {
        this.getDicts('file_config_type').then(response => {
          this.fileConfigTypeOptions = response.data
        })
        this.loadingAllDir()
        listWfConfigFlow({}).then(response => {
          this.getDicts('deal_type').then(res1 => {
            this.getDicts('fund_type').then(res2 => {
              var temp = res1.data.concat(res2.data)
              response.rows.forEach(item => {
                var find = temp.find(obj => obj.dictValue === item.busDataType)
                if (find) {
                  item.busDataTypeLabel = find.dictLabel
                  this.wfConfigFlowOption.push(item)
                }
                this.changeNodeType(false)
              })
            })
          })
        })
      },
      mounted() {
      },
      methods: {
        // 初始化数据
        init(data) {
          this.loading = true
          if (data != null && data.id !== undefined) {
            getFileConfig(data.id).then(response => {
              this.form = response.data
              if (this.isMultiple) {
                if (this.form.documentType.includes('[')) {
                  this.form.documentType = JSON.parse(this.form.documentType)
                }
                if (this.form.documentNonType.includes('[')) {
                  this.form.documentNonType = JSON.parse(this.form.documentNonType)
                }
              }
              this.changeNodeType(false)
              this.loading = false
            })
          } else {
            this.reset()
            this.loading = false
          }
        },
        // 表单重置
        reset() {
          this.form = {
            id: undefined,
            configurationCoding: undefined,
            fileConfigType: 'WDCD',
            documentType: undefined,
            documentNonType: undefined,
            nodeId: undefined,
            nodeType: undefined,
            remark: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined
          }
          this.resetForm('form')
        },
        // 取消按钮
        cancel() {
          this.$parent.$parent.formOpen = false
          this.$parent.$parent.reset()
        },
        // 关闭form页面
        closeForm() {
          // 关闭form页面遮罩层
          this.loading = false
          // 关闭form页面
          if (this.$parent.$parent.formOpen !== undefined) {
            this.$parent.$parent.formOpen = false
          }
          // 刷新list页面
          if (this.$parent.$parent.getList !== undefined) {
            this.$parent.$parent.getList()
          }
        },
        /** 提交按钮 */
        submitForm: function() {
          this.$refs['form'].validate(valid => {
            if (valid) {
              this.loading = true
              console.log(this.form)
              if (this.isMultiple) {
                this.form.documentType = JSON.stringify(this.form.documentType)
                this.form.documentNonType = JSON.stringify(this.form.documentNonType)
              }
              saveFileConfig(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm()
                } else {
                  this.msgError(response.msg)
                }
                this.loading = false
              })
            } else {
              this.locationError(document)
            }
          })
        },
        // 加载全部文件夹
        loadingAllDir() {
          fileClassTreeStructure({ belong: '', parentId: '0' }).then(response => {
            this.fileDirOptions = response.data
            this.checkIfItIsOptionalMain()
            this.loading = false
          })
        },
        // 检查是否可选
        checkIfItIsOptionalMain() {
          this.fileDirOptions.forEach(item => {
            item.isDisabled = item.isBuiltIn === '1'
            this.checkIfItIsOptionalSub(item)
          })
        },
        checkIfItIsOptionalSub(data) {
          if (data !== null && data.children !== null) {
            data.children.forEach(item => {
              item.isDisabled = item.isBuiltIn === '1'
              this.checkIfItIsOptionalSub(item)
            })
          }
        },
        loadFileDirOptions({ action, parentNode, callback }) {
          console.log(action, parentNode, callback)
        },
        currDeptChange(row) {
          console.log(row)
        },
        loadOptions({ action, parentNode, callback }) {
          console.log(action, parentNode, callback)
          if (action === 'LOAD_CHILDREN_OPTIONS') {
            fileClassTreeStructure({ belong: parentNode.belong, parentId: parentNode.id }).then(response => {
              console.log(response)
              var data = response.data
              if (!this.isEmpty(data)) {
                parentNode.children = data
              } else {
                delete parentNode.children
                parentNode.hasChildren = false
              }
              callback()
            }).catch(() => {
              callback()
            })
          }
        },
        changeNodeType(isClear) {
          var val = this.form.nodeType
          if (!this.isEmpty(val)) {
            var find = this.wfConfigFlowOption.find(obj => obj.busDataType === val)
            if (find) {
              this.getAllNode(find.id, 'first', isClear)
            }
          }
        },
        // 查询所有节点-流程依赖节点选择使用
        getAllNode(flowId, nodeType, isClear) {
          var allNodeQuery = {}
          allNodeQuery.flowId = flowId
          allNodeQuery.nodeType = nodeType
          if (isClear) {
            this.form.nodeId = undefined
          }
          listWfConfigNode(allNodeQuery).then(response => {
            this.allNodeList = response.rows
          })
        },
        allNodeNormalizer(node) {
          if (this.isEmpty(node.children)) {
            delete node.children
          }
          return {
            id: node.id,
            label: node.nodeName,
            children: node.children
          }
        },
        // 判断配置编码是否重复
        async checkConfigurationCoding(rule, value, callback) {
          var fileConfig = await findByConfigurationCoding(this.form.configurationCoding)
          if (this.form.id === undefined || this.form.id === null || this.form.id === '') {
            if ((fileConfig.data.length > 0 && this.form.id === undefined) || (fileConfig.data.length > 0 && this.form.id !== undefined)) {
              callback(new Error(this.$t('配置编码不可重复')))
            } else {
              callback()
            }
          } else {
            callback()
          }
        },
        checkDocumentType(rule, value, callback) {
          if (this.form.fileConfigType === 'WDJJ') {
            callback()
          } else {
            if (this.isEmpty(value)) {
              callback(new Error(this.$t('必填信息')))
            } else {
              callback()
            }
          }
        }
      }
    }
</script>
